package top.hidoctor.auscultation.feature.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tang.util.DialogUtil;
import com.tang.util.Event;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.BzrenwubaoAdapter;
import top.hidoctor.auscultation.adapter.ShaixuanAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.BaizhubaoListBean;
import top.hidoctor.auscultation.bean.ShaixuanBean;
import top.hidoctor.auscultation.event.AddLabelSDEvent;
import top.hidoctor.auscultation.event.AuditZdEvent;
import top.hidoctor.auscultation.event.LabelZdEvent;
import top.hidoctor.auscultation.net.c.BaizhubiaoListContract;
import top.hidoctor.auscultation.net.p.BaizhubaoPresenter;
import top.hidoctor.auscultation.net.req.BaizhubaoReq;
import top.hidoctor.auscultation.net.req.LabelZdReq;
import top.hidoctor.auscultation.net.req.PageReq;
import top.hidoctor.auscultation.net.req.SimleReq;
import top.hidoctor.auscultation.view.ChooseBiaozhuPop;

public class BaizhubaoListActivity extends BaseActivity implements BaizhubiaoListContract.View, View.OnClickListener {
    private RecyclerView recycler, rcCondition;
    private BzrenwubaoAdapter adapter;
    private TextView tvAdd, tvShaixuan;
    private ChooseBiaozhuPop chooseBzPop;
    private BaizhubaoPresenter presenter;
    private BaizhubaoReq pageReq;
    private SwipeRefreshLayout refreshLayout;
    private EditText editSearch;
    private List<ShaixuanBean> shaixuanBeanList = new ArrayList<>();
    private DrawerLayout drawer;
    private Button btnChongzhi, btnConfirm;
    private ShaixuanAdapter shaixuanAdapter;
    private SimleReq simleReq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_biaozhubao_list);
        EventBus.getDefault().register(this);
        presenter = new BaizhubaoPresenter(this, this);
        pageReq = new BaizhubaoReq();
        initView();
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        editSearch = findViewById(R.id.edit_search);
        tvAdd = findViewById(R.id.tv_add);

        refreshLayout = findViewById(R.id.refreshLayout);
        recycler = findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter = new BzrenwubaoAdapter(R.layout.item_bz_renwubao, null));

        View view = LayoutInflater.from(this).inflate(R.layout.layout_empty_list, (ViewGroup) recycler.getParent(), false);
        adapter.setEmptyView(view);
        adapter.isFirstOnly(false);
        adapter.openLoadAnimation();
        adapter.openLoadMore(10, true);
        recycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                startActivity(new Intent(BaizhubaoListActivity.this, BiaozhuDetailActivity.class).putExtra("id", adapter.getData().get(position).getId()));
            }
        });


        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hideSoft(recycler);
                refresh();
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            pageReq.setKeyWord(v.getText().toString().trim());
                            refresh();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        adapter.setOnRecyclerViewItemLongClickListener(new BaseQuickAdapter.OnRecyclerViewItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, final int position) {
                showAlertDialog("", "确定要删除吗?", new DialogUtil.DialogButtonClickListener() {
                    @Override
                    public void onPositiveButtonClick(DialogInterface dialog) {
                        dialog.dismiss();
                        presenter.deleteLabel(adapter.getData().get(position).getId());
                    }

                    @Override
                    public void onNegativeButtonClick(DialogInterface dialog) {
                        dialog.dismiss();
                    }
                });
                return true;
            }
        });
        chooseBzPop = new ChooseBiaozhuPop(this);
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseBzPop.show();
            }
        });
        chooseBzPop.setListener(new ChooseBiaozhuPop.ClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.btn_shoudong:
                        startActivity(new Intent(BaizhubaoListActivity.this, ExampleChooseActivity.class).putExtra("type", "1"));
                        break;
                    case R.id.btn_zidong:
                        startActivity(new Intent(BaizhubaoListActivity.this, SendPackageActivity.class).putExtra("type", "1"));
                        break;
                }
            }
        });
        refresh();
        initDrawer();
    }

    /**
     * 初始化 抽屉布局
     */
    private void initDrawer() {
        shaixuanBeanList.add(new ShaixuanBean(false, "标注开始", "10"));
        shaixuanBeanList.add(new ShaixuanBean(false, "标注完成", "20"));
        shaixuanBeanList.add(new ShaixuanBean(false, "标注超时", "30"));
        drawer = findViewById(R.id.drawer);
        rcCondition = findViewById(R.id.rc_condition);
        btnChongzhi = findViewById(R.id.btn_chongzhi);
        btnConfirm = findViewById(R.id.btn_confirm);
        tvShaixuan = findViewById(R.id.tv_shaixuan);
        rcCondition.setLayoutManager(new GridLayoutManager(this, 3));
        rcCondition.setAdapter(shaixuanAdapter = new ShaixuanAdapter(R.layout.item_shaixuan, shaixuanBeanList));
        btnConfirm.setOnClickListener(this);
        btnChongzhi.setOnClickListener(this);
        tvShaixuan.setOnClickListener(this);
        shaixuanAdapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<ShaixuanBean> data = adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setCheck(false);
                }
                data.get(position).setCheck(true);
                adapter.notifyDataSetChanged();
                pageReq.setStatus(data.get(position).getStatus());
            }
        });
    }

    /**
     * 上啦加载
     */
    private void loadMore() {
        pageReq.setPageNo(1 + pageReq.getPageNo());
        presenter.getList(pageReq, refreshLayout);
    }

    /**
     * 下啦刷新
     */
    private void refresh() {
        pageReq.setPageNo(1);
        presenter.getList(pageReq, refreshLayout);
    }

    /**
     * 获取列表数据回调
     *
     * @param bean
     */
    @Override
    public void getListSuc(BaizhubaoListBean bean) {
        if (pageReq.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    /**
     * 删除数据回调
     */
    @Override
    public void deleteLabelSuc() {
        refresh();
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_shaixuan:
                drawer.openDrawer(Gravity.RIGHT);
                break;
            case R.id.btn_chongzhi:
                List<ShaixuanBean> shaixuanList = shaixuanAdapter.getData();
                for (int i = 0; i < shaixuanList.size(); i++) {
                    shaixuanList.get(i).setCheck(false);
                }
                shaixuanAdapter.notifyDataSetChanged();
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                pageReq.setStatus("");
                pageReq.setKeyWord("");
                refresh();
                break;
            case R.id.btn_confirm:
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                pageReq.setKeyWord("");
                refresh();
                break;
        }
    }

    /**
     * 网络请求 错误处理
     *
     * @param code
     * @param msg
     */
    @Override
    public void onError(String code, String msg) {
        super.onError(code, msg);
        showToast(msg);
        refreshLayout.setRefreshing(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LabelZdEvent event) {
        refresh();
    }

    /**
     * 事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddLabelSDEvent event) {
        refresh();
    }
}
